if (!window._uniBridgeListeners) {
    window._uniBridgeListeners = new Map();
}

const DEFAULT_TIMEOUT = 5000;

// 初始化方法，绑定全局接收器
export function initUniBridge(uni) {
    window.uni = uni;

    window.receiveMessageFromApp = function (msg) {
        const data = typeof msg === 'string' ? JSON.parse(msg) : msg;
        const requestId = data.requestId;

        if (requestId && window._uniBridgeListeners.has(requestId)) {
            const cb = window._uniBridgeListeners.get(requestId);
            cb(data.data);
            window._uniBridgeListeners.delete(requestId);
        } else {
            console.warn('未找到 requestId 对应回调：', requestId, msg);
        }
    };
}

// 核心发送方法
export function sendMessageWithPromise({ action, sql }) {
    const requestId = `${action}-${Date.now()}-${Math.random()}`;
    const payload = { action, sql, dbName: 'main', requestId };

    return new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
            window._uniBridgeListeners.delete(requestId);
            reject(new Error('请求超时'));
        }, DEFAULT_TIMEOUT);

        window._uniBridgeListeners.set(requestId, (data) => {
            clearTimeout(timeout);
            resolve(data);
        });

        if (window.uni && window.uni.webView) {
            window.uni.webView.postMessage({ data: payload });
        } else {
            clearTimeout(timeout);
            reject(new Error('uni.webView 未定义'));
        }
    });
}

// 快捷方法封装
export const createTableSql = (sql) => sendMessageWithPromise({ action: 'createSql', sql });
export const selectSql = (sql) => sendMessageWithPromise({ action: 'selectSql', sql });
export const addSql = (sql) => sendMessageWithPromise({ action: 'addSql', sql });
export const deleteSql = (sql) => sendMessageWithPromise({ action: 'deleteSql', sql });
export const updateSql = (sql) => sendMessageWithPromise({ action: 'updateSql', sql });
